package com.twetec.cms.adapter.pc.backend.controller.search;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.search.SearchArticlePO;
import com.twetec.cms.model.po.website.ArticleExtendPO;
import com.twetec.cms.model.po.website.ArticlePO;
import com.twetec.cms.model.vo.search.SearchArticlePageListVO;
import com.twetec.cms.model.vo.website.ArticlePageListVO;
import com.twetec.cms.service.search.SearchArticleService;
import com.twetec.cms.service.website.ArticleExtendService;
import com.twetec.cms.service.website.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhaichangzheng
 * @Date: 2022/2/23 17:57 （日期和时间）
 */

@Api(tags = "全文检索")
@RestController
@RequestMapping("/search/article")
public class SearchArticleController {

    @Autowired
    private SearchArticleService searchArticleService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleExtendService articleExtendService;


    @ApiOperation(value = "检索列表", notes = "检索列表")
    @GetMapping("/page-search-article-list")
    public R<SearchArticlePageListVO> pageSearchArticleList(
            @ApiParam(value = "文章标题/内容", required = true, example = "标题") @RequestParam(required = false) String articleTitle,
            @ApiParam(value = "作者", required = false, example = "鲁迅") @RequestParam(required = false) String authorName,
            @ApiParam(value = "栏目id的拼接,用英文逗号隔开", required = false, example = "123,123,1212") @RequestParam(required = false) String columnIds,
            @ApiParam(value = "创建时间开始（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date createStartTime,
            @ApiParam(value = "创建时间结束（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date createEndTime,
            @ApiParam(value = "根据发布时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtReleaseTimeStart,
            @ApiParam(value = "根据发布时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtReleaseTimeEnd,
            @ApiParam(value = "文章来源", required = false, example = "新华社") @RequestParam(required = false) String articleOrigin,
            @ApiParam(value = "文章状态(全部ALL,草稿CAO_GAO,待审核DAI_SHEN_HE,待修改DAI_XIU_GAI,已发布YI_FA_BU,已下架YI_XIA_JIA,已过期YI_GUO_QI)", required = false, example = "YI_GUO_QI") @RequestParam(required = false) String articleStatus,
            @ApiParam(value = "seoKeywords", required = false, example = "新闻") @RequestParam(required = false) String seoKeywords,
            @ApiParam(value = "文章类型(图文资讯TU_WEN_ZI_XUN,下载文件XIA_ZAI_WEN_JIAN,跳转链接TIAO_ZHUAN_LIAN_JIE,公告资讯GONG_GAO_ZI_XUN)", required = false, example = "GONG_GAO_ZI_XUN") @RequestParam(required = false) String articleType,
            @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        // 参数校验
        if (null == page || !ValidateUtil.Number(page) || page < 0) return R.failureRequestParam().msg("页码为空或格式不正确");
        if (null == limit || !ValidateUtil.Number(limit) || limit < 0) return R.failureRequestParam().msg("页条目数为空或格式不正确");

        // 字符串类型的参数null的设置为""
        // 文章标题
        if (null == articleTitle) {
            return R.failure().msg("请输入文章标题或内容");
        }
        // 作者名字
        if (null == authorName)  authorName = "";
        // 栏目id
        ArrayList<String> columnIdList = new ArrayList<>();
        if (null != columnIds)  {
            String[] split = columnIds.split(",");
            for (String s : split) {
                columnIdList.add(s);
            }
        }
        // 文章来源
        if (null == articleOrigin)  articleOrigin = "";
        // 文章状态
        if (null == articleStatus)  articleStatus = "";
        if (null == seoKeywords)  seoKeywords = "";
        if (null == articleType)  articleType = "";

        SearchArticlePageListVO searchArticlePageListVO;
        try {
            searchArticlePageListVO = searchArticleService.pageSearchList(articleTitle, articleTitle, authorName, columnIdList, createStartTime, createEndTime,
                    gmtReleaseTimeStart, gmtReleaseTimeEnd, articleOrigin, articleStatus, seoKeywords, articleType, page, limit);
            return R.success().data(searchArticlePageListVO);
        } catch (Exception e) {
            return R.failure().msg("检索失败");
        }
    }

    @ApiOperation(value = "替换", notes = "替换")
    @PostMapping("/replace")
    public R replace(
            @ApiParam(value = "文章id的拼接,用英文逗号隔开", required = true, example = "123,123,1212") @RequestParam(required = false) String articleIds,
            @ApiParam(value = "原内容", required = true, example = "新华社") @RequestParam(required = false) String originContent,
            @ApiParam(value = "替换内容", required = true, example = "腾讯网") @RequestParam(required = false) String replaceContent) {

        // 进行参数校验
        if (null == articleIds || StringUtils.isBlank(articleIds)) {
            return R.failure().msg("请选择文章");
        }
        if (null == originContent || StringUtils.isBlank(originContent)) {
            return R.failure().msg("原内容不能为空");
        }
        if (null == replaceContent || StringUtils.isBlank(replaceContent)) {
            return R.failure().msg("替换内容不能为空");
        }

        String[] split = articleIds.split(",");
        ArrayList<String> articleIdList = new ArrayList<>();
        for (String s : split) {
            articleIdList.add(s);
        }

        // 替换文章标题
        articleService.replace(articleIdList, originContent, replaceContent);
        // 替换内容
        articleExtendService.replace(articleIdList, originContent, replaceContent);

        try {
            // 更新全局检索中的文章
            searchArticleService.deleteDocBatchByArticleIds(articleIdList);
            // 整理添加的数据
            ArrayList<SearchArticlePO> searchArticlePOS = new ArrayList<>();
            for (String articleId : articleIdList) {
                ArticlePO articlePO = articleService.getById(Long.parseLong(articleId));
                QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
                articleExtendPOQueryWrapper.eq("ARTICLE_ID", Long.parseLong(articleId));
                ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);
                SearchArticlePO searchArticlePO = p_copyArticleToSearchArticle(articlePO, articleExtendPO.getContent(), articleExtendPO.getSeoKeywords());
                searchArticlePOS.add(searchArticlePO);
            }
            // 添加到全局检索中
            searchArticleService.addDocBatch(searchArticlePOS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.success();
    }

    /**
     * 查询文章模型转换
     * @param article
     * @param content
     * @param seoKeywords
     * @return
     */
    private SearchArticlePO p_copyArticleToSearchArticle(ArticlePO article, String content, String seoKeywords) {
        SearchArticlePO searchArticlePO = new SearchArticlePO();
        searchArticlePO.setArticleId(String.valueOf(article.getId()));
        searchArticlePO.setArticleTitle(article.getTitle());
        searchArticlePO.setArticleContent(content);
        searchArticlePO.setArticleType(article.getType());
        searchArticlePO.setArticleOrigin(article.getOrigin());
        searchArticlePO.setArticleStatus(article.getArticleStatus());
        searchArticlePO.setSiteId(String.valueOf(article.getSiteId()));

        searchArticlePO.setColumnId(String.valueOf(article.getColumnId()));
        searchArticlePO.setColumnName(article.getColumnName());
        searchArticlePO.setColumnXPath(article.getColumnXpath());
        searchArticlePO.setAuthorName(article.getAuthor());

        searchArticlePO.setSeoKeywords(seoKeywords);
        searchArticlePO.setReleaseChannel(article.getReleaseChannel());
        searchArticlePO.setCreateTime(article.getGmtCreate());
        searchArticlePO.setReleaseTime(article.getReleaseTime());
        return searchArticlePO;
    }

}
